package jgl.vajra.management.part.mine.pop;

import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.ConditionTypeBean;
import jgl.vajra.management.bean.PopConditionTypeBean;
import jgl.vajra.management.constant.Constant;
import jgl.vajra.management.databinding.PopConditionTypeBinding;
import jgl.vajra.management.databinding.PopItemConditionTypeBinding;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.management.widget.databindingadapter.BaseDataBindingDecorator;
import jgl.vajra.management.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

public class ConditionTypePop implements BaseBindingItemPresenter<PopConditionTypeBean.PopConditionTypeItemBean> {

    private FragmentActivity activity;
    private View mPopRootView;
    private PopupWindow menuPop;
    private ConditionTypePop.ConditionTypeListener listener;
    private List<PopConditionTypeBean> list;
    private SingleTypeBindingAdapter adapter;

    public ConditionTypePop(FragmentActivity activity) {

        this.activity = activity;
    }


    private void initPopupWindow() {
        mPopRootView = View.inflate(UIUtils.getContext(), R.layout.pop_condition_type, null);
        PopConditionTypeBinding mBinding = DataBindingUtil.bind(mPopRootView);

        menuPop = new PopupWindow(mPopRootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        menuPop.setOutsideTouchable(false);
        menuPop.setBackgroundDrawable(new BitmapDrawable());
        menuPop.setFocusable(true);// 点击空白处时，隐藏掉pop窗口
        menuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //popupwindow消失的时候恢复成原来的透明度
                backgroundAlpha(1f);
            }
        });
        mBinding.setView(this);

        list = new ArrayList<>();

        requestNetData();


        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        adapter = new SingleTypeBindingAdapter(activity, null, R.layout.pop_item_condition_type);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);
        adapter.setItemDecorator((BaseDataBindingDecorator<PopConditionTypeBean, PopItemConditionTypeBinding>) (binding, position, viewType, data) -> {

            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(activity, data.itemList, R.layout.pop_item_condition_type_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);
            itemAdapter.setItemPresenter(this);

        });
    }

    public void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("tag", Constant.USER_TYPE);
        RetrofitJsonManager.getInstance().getApiService().getConditionTypeData(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<ConditionTypeBean>(false, null) {
                    @Override
                    public void _onNext(ConditionTypeBean data) {

                        PopConditionTypeBean popConditionTypeBean = new PopConditionTypeBean();
                        popConditionTypeBean.title = "收入";
                        List<PopConditionTypeBean.PopConditionTypeItemBean> itemList = new ArrayList<>();
                        itemList.addAll(data.incomeData);
                        popConditionTypeBean.itemList = itemList;
                        list.add(popConditionTypeBean);

                        PopConditionTypeBean popConditionTypeBean1 = new PopConditionTypeBean();
                        popConditionTypeBean1.title = "支出";
                        List<PopConditionTypeBean.PopConditionTypeItemBean> itemList1 = new ArrayList<>();
                        itemList1.addAll(data.expenditureData);
                        popConditionTypeBean1.itemList = itemList1;
                        list.add(popConditionTypeBean1);
                        adapter.refresh(list);
                    }
                });
    }

    public void showPopupWindow(View v) {
        if (menuPop == null)
            initPopupWindow();
        int[] location = new int[2];
        v.getLocationOnScreen(location);  //获取控件的位置坐标
        //获取自身的长宽高
        mPopRootView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        backgroundAlpha(0.5f);

//        menuPop.showAtLocation(v, Gravity.NO_GRAVITY, (int) (location[0] - DisplayUtils.getDimension(R.dimen.dp_4)), (int) (location[1] - mPopRootView.getMeasuredHeight() - DisplayUtils.getDimension(R.dimen.dp_4)));  //显示指定控件的上方
        menuPop.showAsDropDown(v, 0, 0);    //显示指定控件的下方
    }

    public boolean isShowing() {
        return menuPop != null && menuPop.isShowing();
    }

    public void dismiss() {
        if (menuPop != null && menuPop.isShowing())
            menuPop.dismiss();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        if (activity == null) return;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);

    }

    @Override
    public void onItemClick(int position, PopConditionTypeBean.PopConditionTypeItemBean itemData) {
        itemData.isClick = !itemData.isClick;
        adapter.refresh();
    }

    public void setConditionTypeListener(ConditionTypePop.ConditionTypeListener listener) {
        this.listener = listener;

    }

    public interface ConditionTypeListener {
        void onDetermine(String conditionType);
    }

    //重置
    public void onReset() {
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.get(i).itemList.size(); j++) {
                list.get(i).itemList.get(j).isClick = false;
            }
        }
        adapter.refresh();
        if (listener != null) {
            listener.onDetermine("");
        }
        dismiss();
    }

    //确认
    public void onDetermine() {
        StringBuilder conditionType = new StringBuilder();
        if (listener != null) {

            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.get(i).itemList.size(); j++) {
                    if (list.get(i).itemList.get(j).isClick) {
                        conditionType.append("type=").append(list.get(i).itemList.get(j).type).append(" or ");
                    }
                }
            }
            if (TextUtils.isEmpty(conditionType)){
                ToastUtils.showShort("请选择收支类别");
                return;
            }
            String newConditionType = conditionType.substring(0, conditionType.length() - 4);
            listener.onDetermine(" and (" + newConditionType + ")");
        }
        dismiss();
    }
}